package com.xjm_cloud_admin.security.service;

import com.xjm_cloud_admin.constant.CacheConstants;
import com.xjm_cloud_admin.constant.Constants;
import com.xjm_cloud_admin.redis.RedisCache;
import com.xjm_cloud_admin.security.pojo.LoginUser;
import com.xjm_cloud_admin.util.IdUtils;
import com.xjm_cloud_admin.util.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author 浪漫写尽歌谱
 */
@Component
public class ShareTokenService {
    private static final Logger log = LoggerFactory.getLogger(ShareTokenService.class);

    // 令牌自定义标识
    @Value("${token.share.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.share.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.share.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }


    /**
     * 验证令牌有效期
     *
     * @param request 请求
     * @return 令牌
     */
    public String verifyToken(HttpServletRequest request) {
        String token = getToken(request);
        if (org.apache.commons.lang3.StringUtils.isEmpty(token)) {
            return "";
        }
        Claims claims = parseToken(token);
        long savingTime = (long) claims.get(Constants.FILE_EXPIRE_TIME_KEY);
        long currentTime = System.currentTimeMillis();
        if (currentTime > savingTime) {
            return "";
        }
        String value = (String) claims.get(Constants.FILE_SHARE_TOKEN_KEY);
        return value.split("_")[1];
    }

    /**
     * 验证令牌有效期
     *
     * @return 令牌
     */
    public String verifyByToken(String token) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(token)) {
            return "";
        }
        Claims claims = parseToken(token);
        long savingTime = (long) claims.get(Constants.FILE_EXPIRE_TIME_KEY);
        long currentTime = System.currentTimeMillis();
        if (currentTime > savingTime) {
            return "";
        }
        String value = (String) claims.get(Constants.FILE_SHARE_TOKEN_KEY);
        return value.split("_")[1];
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取请求token
     *
     * @param request 请求
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 创建分享文件token
     *
     * @param shareId 分享id
     * @return 分享文件所需token
     */
    public String createToken(String shareId) {
        Map<String, Object> claims = new HashMap<>();
        String value = IdUtils.fastUUID() + "_" + shareId;
        claims.put(Constants.FILE_SHARE_TOKEN_KEY, value);
        claims.put(Constants.FILE_EXPIRE_TIME_KEY, System.currentTimeMillis() + expireTime * MILLIS_MINUTE);
        return createToken(claims);
    }


}
